<template>
  <div class="authen">
    <div></div>
    <span>{{ tip }}</span>
    <!-- <button @click="test">test</button> -->
  </div>
</template>

<script>
import Vue from "vue";
import { getAuthen } from "@/utils/getAuthen";
import querystring from "querystring";
import { mapMutations, mapActions } from "vuex";
import { getEnterpriseId } from "@/utils/getEnterpriseId";

export default Vue.extend({
  head() {
    return {
      title: "激活会员卡"
    };
  },
  data() {
    return {
      redirect: "",
      tip: "会员卡激活成功",
      mobilePhone: ""
    };
  },
  async created() {
    try {
      let type = 0;
      // 0 获取openid 常规流程
      // 1 用户第一次，网站直接跳转 获取phone 正常流程
      // 2 用户通过会员卡界面激活，有openId无activateTicket 可能没有outerStr 其他同1 特殊流程
      // 3 已经激活的用户，木有了缓存，二次进入 正常流程

      let state = this.$route.query.state; // 0
      let code = this.$route.query.code; // 0

      let outerStr = this.$route.query.outer_str; // 1

      let cardId = this.$route.query.card_id; // 1 2
      let openId = this.$route.query.openid; // 1 2 3
      let activateTicket = this.$route.query.activate_ticket; // 1 2
      let encryptCode = this.$route.query.encrypt_code; // 1 2

      let phone = this.$route.query.phone; // 3
      let unionId = this.$route.query.unionid; // 3
      let originUrl = this.$route.query.originurl; // 3

      let enterpriseId = "";

      let extStr = "";
      if (!!state) {
        extStr = state;
        type = 0;
      } else if (!!outerStr) {
        extStr = outerStr;
        type = 1;
      } else if (!!cardId && !activateTicket) {
        type = 2;
      } else if (!!phone) {
        type = 3;
        extStr = originUrl;
      }

      // 用户直接访问
      if (!state && !outerStr && !cardId && !phone) {
        this.tip = "此页不支持直接访问";
        return;
      }

      // 解析url
      const urlInfo = this.parseExtStr(extStr);
      // 保存分享者id（用户通过推荐有奖分享出来的页面进来时，url会携带一个分享者的id，字段名叫shareUserId）
      if (urlInfo.searchObj.shareUserId) {
        localStorage.setItem("shareUserId", urlInfo.searchObj.shareUserId);
      }
      if (type == 2) {
        //根据会员卡id拉取油企id 重定位跳转地址
        const enterpriseIdPro = await this.queryEnterpriseIdByCardId(cardId);
        enterpriseId = enterpriseIdPro.enterpriseId;
        this.redirect = "/" + enterpriseId + "/my/";

        // const phoneRes = await this.getPhoneByAuthenInfo(enterpriseId);
        // phone = phoneRes.phone;
        // unionId = phoneRes.unionId;

        // this.$store.commit("authen/setEnterpriseId", enterpriseId)
        // this.$store.commit("authen/setOpenId", openId)
        // this.$store.commit("authen/setPhone", phone)
        // this.$store.commit("authen/setUnionId", unionId)

        // this.handleGotoPage()
      } else {
        // 网址里面包含油企id，跳转网址在urlInfo里
        enterpriseId = urlInfo.enterpriseId;
        // 充值界面特殊处理
        if (urlInfo.firstUrl == "/charge/") {
          enterpriseId = urlInfo.searchObj.enterpriseId;
        } else if (urlInfo.firstUrl == "/plus/") {
          enterpriseId = urlInfo.searchObj.enterpriseId;
        }

        this.redirect = urlInfo.fullUrl;
      }
      // 没有油企id，强退
      if (!enterpriseId) {
        this.tip = "请访问站点网站";
        return;
      }

      if (type == 0) {
        // openid 认证 回来 -> 开始手机认证
        const openIdRes = await this.queryOpenIdByEnterpriseId(enterpriseId);
        const openId = openIdRes.openId;
        this.$store.commit("authen/setEnterpriseId", enterpriseId);
        this.$store.commit("authen/setOpenId", openId);
        if (openIdRes.retCode && openIdRes.retCode === 600) {
          // 这里做一下清空缓存？
          alert("1003,拉取openId失败,请重试~");
          localStorage.clear();
        } else {
          getAuthen(extStr);
        }
        return; //退出整个getAuthen方法
      } else if (type == 1 || type == 2) {
        // type == 1  正常流程
        const phoneRes = await this.getPhoneByAuthenInfo(enterpriseId);
        phone = phoneRes.phone;
        unionId = phoneRes.unionId;

        this.$store.commit("authen/setEnterpriseId", enterpriseId);
        this.$store.commit("authen/setOpenId", openId);
        this.$store.commit("authen/setPhone", phone);
        this.$store.commit("authen/setUnionId", unionId);

        this.handleGotoPage();
      } else if (type == 3) {
        this.$store.commit("authen/setEnterpriseId", enterpriseId);
        this.$store.commit("authen/setOpenId", openId);
        this.$store.commit("authen/setPhone", phone);
        this.$store.commit("authen/setUnionId", unionId);

        this.handleGotoPage();
      }
    } catch (err) {
      console.log(err);
      const message = !!err.message ? err.message : err;
      alert(message);
    }

    // this.getAppId(id).then(()=>{
    //   this.getPhoneByAuthenInfo();
    // }).catch((res)=>{
    //   alert("拉取appId失败")
    // })
  },
  methods: {
    test() {
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxab62cad69f646815&redirect_uri=https%3A%2F%2Fyh.xailife.com%2Fcash-register%2Fpages%2Fcash%2Findex%3Ffmno%3D301015200001138%26clientSerialNo%3D111111%26platform%3D2&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
    },
    parseExtStr(extStr) {
      let searchObj;
      let searchStr;
      let enterpriseId;

      const [url, str] = extStr.split(".");
      if (str !== undefined) {
        searchStr = str.replace(/-/g, "&").replace(/_/g, "=");
        searchObj = querystring.parse(searchStr);
      } else {
        searchStr = "";
        searchObj = {};
      }

      let enterpriseIdArr = url.replace(/\//, "").match(/^\d{1,}/);
      if (enterpriseIdArr == null) {
        enterpriseId = "";
      } else {
        enterpriseId = enterpriseIdArr[0];
      }

      return {
        fullUrl: url + (searchStr != "" ? "?" : "") + searchStr,
        firstUrl: url,
        searchObj,
        enterpriseId
      };
    },
    async getUserInfo() {
      console.log("手机号getUserInfo" + this.phone);
      try {
        const infoData = await this.$axios.$get("/selectMemberInfo", {
          params: {
            enterpriseId: this.enterpriseId,
            mobilePhone: this.phone
          }
        });

        if (infoData.retCode !== 0) {
          throw new Error(infoData.message);
        }
        if (!infoData.data) {
          localStorage.clear(); // 清空缓存
          throw new Error("1003,查询不到该用户信息,请重新进入");
        }

        this.setUserInfo(infoData.data);
        console.log(infoData.data);
      } catch (error) {
        alert(error);
      }
    },
    async handleGotoPage() {
      await this.getUserInfo();
      this.$router.replace({
        path: this.redirect
      });
    },
    // havingOpenIdAuthen(enterpriseId,extStr) {
    //   // const appIdPro = await this.queryAppIdByEnterpriseId(enterpriseId);

    // },
    async queryOpenIdByEnterpriseId(enterpriseId) {
      const code = this.$route.query.code;
      const gzhAuthenRes = await this.$axios.$get("/getGzhAuthorizeInfo", {
        params: {
          code,
          enterpriseId: enterpriseId
        }
      });
      if (gzhAuthenRes.retCode !== 0) {
        return Promise.reject({
          message: "拉取openId失败",
          retCode: 600
        });
      }
      const openId = gzhAuthenRes.data.openid;
      console.log("拉取的openId为", openId);
      return Promise.resolve({
        enterpriseId,
        openId
      });
    },
    async getPhoneByAuthenInfo(enterpriseId) {
      let shareUserId = Number(localStorage.getItem("shareUserId")); // 获取分享者ID
      const encryptCode = this.$route.query.encrypt_code;
      const openId = this.$route.query.openid;
      const activateTicket = this.$route.query.activate_ticket;

      if (
        !!enterpriseId &&
        !!encryptCode &&
        !!openId &&
        !!activateTicket &&
        false
      ) {
        const gzhAuthenRes = await this.$axios.$post("/selectCardMobilePhone", {
          enterpriseId: enterpriseId,
          openId: openId,
          activateTicket: activateTicket,
          encryptCode: encryptCode
        });
        if (gzhAuthenRes.retCode !== 0) {
          return Promise.reject("拉取手机号失败");
        }
        const phone = gzhAuthenRes.data.phone;
        const unionId = gzhAuthenRes.data.unionid;
        // commit("setOpenId", openId)
        // commit ("setPhone", phone)
        // commit ("setUnionId", unionId)
        return Promise.resolve({
          phone,
          unionId
        });
      } else if (!!enterpriseId && !!encryptCode && !!openId) {
        // 如果用户是通过推荐有奖分享出去的链接进来时，给后端传一个分享者id
        let gzhAuthenRes;
        if (shareUserId) {
          gzhAuthenRes = await this.$axios.$post("/selectWxMemberCardInfo", {
            enterpriseId: enterpriseId,
            openId: openId,
            encryptCode: encryptCode,
            userId: shareUserId
          });
        } else {
            // 如果没有shareUserId ，则证明不是通过分享链接进来
            let inviteUserId= this.$route.query.inviteUserId || localStorage.getItem("recommenderid")
            let query={
                enterpriseId: enterpriseId,
                openId: openId,
                encryptCode: encryptCode,
              }
              if(inviteUserId!='null'){ 
                query['inviteUserId']=inviteUserId
              }
              console.log('authen页面 ，则证明不是通过分享链接进来',query)
              gzhAuthenRes = await this.$axios.$post("/selectWxMemberCardInfo",query);
          }
        if (gzhAuthenRes.retCode !== 0) {
          return Promise.reject(gzhAuthenRes.message);
        }
        const phone = gzhAuthenRes.data.mobilePhone;
        const unionId = gzhAuthenRes.data.unionid;
        return Promise.resolve({
          phone,
          unionId
        });
      } else {
        throw new Error("authen参数不全");
      }
    },
    async queryEnterpriseIdByCardId(cardId) {
      const enterpriseIdPro = await this.$axios.$get(
        "/selectEnterpriseIdByCardId",
        {
          params: {
            cardId
          }
        }
      );
      if (enterpriseIdPro.retCode != 0) {
        return Promise.reject("拉取EnterpriseId失败");
      }
      return Promise.resolve({
        cardId: cardId,
        enterpriseId: enterpriseIdPro.data
      });
    },
    async queryAppIdByEnterpriseId(enterpriseId) {
      const appIdRes = await this.$axios.$get("/getStationGzhAppId", {
        params: {
          enterpriseId
        }
      });
      if (appIdRes.retCode != 0) {
        return Promise.reject("获取appid失败");
      }
      // commit("setAppId", appIdRes.data.appId)
      return Promise.resolve({
        enterpriseId,
        appId: appIdRes.data.appId
      });
    },
    ...mapMutations({
      setEnterpriseId: "authen/setEnterpriseId",
      setAppId: "authen/setAppId",
      setTempEnterpriseId: "setTempEnterpriseId",
      setUserInfo: "authen/setUserInfo"
    })
    // ...mapActions({
    //   getAppId: "authen/getAppId",
    // }),
  }
});
</script>

<style>
.authen {
  width: 100vw;
  height: 100vh;
  position: relative;
}
.authen div {
  position: absolute;
  top: 2.38rem;
  left: 2.7rem;
  width: 2.16rem;
  height: 2.16rem;
  background: url(../static/wxpic.jpg) no-repeat 0 0;
  background-size: 100% 100%;
}
.authen span {
  position: absolute;
  top: 5.22rem;
  width: 7.5rem;
  text-align: center;
  height: 0.56rem;
  font-size: 0.3rem;
  color: #000000;
  line-height: 0.56rem;
  font-family: PingFangSC-Regular, PingFang SC;
}
</style>
